package com.yy.QSManage.exception;

import com.yy.QSManage.common.Result;
import com.yy.QSManage.tool.DateTool;
import com.yy.QSManage.tool.RequestBuffUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class ExceptionHandler {

    /**
     * 自定义业务异常
     * 拦截处理控制器里对应的异常。
     * @param ex BaseServiceException
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(value = ServiceException.class)
    public Result<Void> tkpcServiceException(HttpServletRequest request, ServiceException ex) {
        logPrint(request, ex);
        return Result.error(ex.getMessage(), ex.getCode());
    }


    /**
     * 全局异常
     * @param request
     * @param ex
     * @return
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
    public Result<Void> handlerException(HttpServletRequest request, Exception ex) {
        logPrint(request, ex);
        return Result.error(ex.getMessage());
    }

    /**
     * 日志打印
     * @param request
     * @param ex
     * @return: void
     * @author: HuDeHong
     * @date: 2023-05-16 10:20
     */
    private void logPrint(HttpServletRequest request, Exception ex){
        log.error("--------异常日志--------");
        log.error("时间：" + DateTool.SDF.format(new Date()));
        log.error("接口：" + request.getRequestURI());
        log.error("请求方式：" + request.getMethod());
        log.error("body：\n"+ RequestBuffUtil.getBody());
        log.error("消息：" + ex.getMessage(), ex);
    }
    /**
     * 参数异常统一处理
     * @param exception
     * @return
     */
    @ResponseBody
    @org.springframework.web.bind.annotation.ExceptionHandler(MethodArgumentNotValidException.class)
    public Result validationException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        if (bindingResult.hasErrors()) {
//            Map<String,String> map = new HashMap<>(100);
            List<String> list = new ArrayList<>();
            //获取所有错误信息
            bindingResult.getFieldErrors().forEach((item)->{
                //获取错误属性名
                String field = item.getField();
                //获取单个错误提示
                String message = field+item.getDefaultMessage();
                list.add(message);
                log.info("参数异常信息："+field+" = "+message);
            });
            return Result.error(list.toString());
        } else {
            log.info("系统异常：" + exception);
            return Result.error("系统异常");
        }
    }

}
